import { s_getSelectTree, s_queryBaseData } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormInstance, ProFormText, ProFormTreeSelect, ProTable } from "@ant-design/pro-components";
import { Button, Col, Divider, message, Modal, Row, Space, TreeSelect } from "antd";
 
import { useRef, useState } from "react";

// 本组件，添加了按类别查找2025-01-19
//本组件，在原2的基础上，添加了返回现存量数据：quantity_stock,quantity_islock---2025-04-17
const App:React.FC<{type:any,setData:any,x_id:any}>=(props)=>{
    const [open,setOpen]=useState(false);
    
    const [materials,setMaterials]=useState<DataType[]>([]);
    // const [userDefines,setUserDefines]=useState([]);
    // const [material,setMaterial]=useState<any>();
    const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);
    const [categoryOption,setCategoryOption]=useState([]);
    const [selectCategoryID,setSelectCategoryID]=useState<any[]>([]);

    const form_ref=useRef<ProFormInstance>();
    const table_ref=useRef<ActionType>();

    function getMaterial(){
        setOpen(true);
    }

    async function findMaterial(){
      const fdata2=form_ref.current?.getFieldsValue();
       const fdata={...fdata2,category_id:selectCategoryID};
      //  alert(JSON.stringify(fdata));
      const x=await s_queryBaseData({x_id:props.x_id,source:'v_material_query3',tdata:fdata});
      if(x.success){
        message.success('查询成功');
        //返回
        setMaterials(x.data[0]);
        // setUserDefines(x.data[1]);
      }else
       message.error('查询失败，请联系管理员');

    }; 

    interface DataType{
      id:number,
      code:string,
      name:string,
      invstd:string,
      invstd2:string,
      munit_name:string,
    }
    const columns:ProColumns<DataType>[]=[
      {dataIndex:'id',hidden:true},
      {dataIndex:'code',title:'编码'},
      {dataIndex:'name',title:'名称'},
      {dataIndex:'invstd',title:'规格'},
      {dataIndex:'invstd2',title:'型号'},
      {dataIndex:'munit_name',title:'计量单位'},
    ];

    function onClose(){
      setSelectCategoryID([]);
      setOpen(false);
      // props.setData({});
    }
    function onOk(){
      props.setData(selectedRecords);
      setSelectCategoryID([]);
      setOpen(false);
     }

     var arr:any[]=[];
     //定义一个递归函数，获取选中节点下的所有key
    //  function getNodeKeys(node:{key:any,title:any,children:any[]}){
       function getNodeKeys(node:any){
          if(node.children.length>0)
                node.children.map((item:any)=>{
                   arr.push(item.value);
                   if(item.children.length>0){
                        arr.push(getNodeKeys(item));
                   }
               });
        }
     //选择商品分类下拉列表框
         function getCategoryIds(node:any){
           arr=[];//先置为空，再取数据
           arr.push(node.value);
           getNodeKeys(node);
           setSelectCategoryID(arr.filter((item)=>item!=null));
          //  alert(JSON.stringify(arr));
          }

    return (
        <>
          <Button onClick={()=>getMaterial()}>选择商品</Button>
          <Modal open={open} closable destroyOnClose onClose={()=>onClose()} onCancel={()=>onClose()}
                onOk={()=>onOk()} width={'70%'} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
            >
              <ProCard title='选择商品'  style={{height:800}}
                extra={<Space>
                  <Button onClick={()=>onOk()}>确定</Button>
                  <Button onClick={()=>onClose()}>取消</Button>
                </Space>}
              >
              <ProForm formRef={form_ref}  labelAlign="left" layout="horizontal" labelCol={{offset:0,span:5}}
                 submitter={false} 
                 onFinish={()=>findMaterial()}
              >
                   <Row gutter={8}>
                    <Col span={10}> 
                       <ProFormText name='code' label='商品编码' width={300}/> 
                       <ProFormTreeSelect name='category_id' label='商品类别' allowClear  width={300}
                        request={async ()=>{
                            const x=await s_getSelectTree({x_id:1,source:'material_category'});
                            // alert(JSON.stringify(x.data));
                            setCategoryOption(x.data);
                            return x.data;
                          }}
                        fieldProps={{
                          showSearch:true,
                          onSelect(value, option) {
                            // alert(JSON.stringify(option));
                            getCategoryIds(option);
                          },
                          treeNodeFilterProp:'title',
                          treeDefaultExpandAll:true,
                        }}
                       />
                    </Col>
                    <Col span={4}></Col>
                    <Col span={10}> 
                       <ProFormText name='name' label='商品名称'  width={300}/> 
                       <ProFormText name='invstd' label='规格'  width={300}/> 
                      </Col>
                  </Row>
                   <Divider ><Button onClick={()=>form_ref.current?.submit()} style={{width:300}}>开始查询</Button></Divider>
               </ProForm>
              {/* {JSON.stringify(material)} */}
              <ProTable<DataType>
                    actionRef={table_ref}
                    dataSource={materials}
                    columns={columns}
                    rowKey='id'
                    pagination={{
                      pageSize:10,
                      showQuickJumper:true,
                    }}
                    rowSelection={{
                      type:props.type,
                      onChange(selectedRowKeys, selectedRows, info) {
                        // setMaterial({material:selectedRows[0],
                        //              userdefine:userDefines.filter((item:any)=>item.material_id==selectedRows[0].id)});
                        // props.setData({material:selectedRows[0],
                        //   userdefine:userDefines.filter((item:any)=>item.material_id==selectedRows[0].id)});
                        setSelectedRecords(selectedRows);
                        // alert(JSON.stringify(material));
                      },
                    }}
                    scroll={{y:300}}
                    search={false}
                    />
            </ProCard>
          </Modal>
        </>
    )
}

export default App;
